import { Button, Grid, Modal } from 'antd-mobile'
import React, { useCallback } from 'react'
import { useEffect } from 'react'
import { useState } from 'react'

import { API, BASE_URL, isAuth, removeToken } from '../../utils'

import styles from './index.module.css'

// 菜单数据
const menus = [
  { id: 1, name: '我的收藏', iconfont: 'icon-coll', to: '/favorite' },
  { id: 2, name: '我的出租', iconfont: 'icon-ind', to: '/rent' },
  { id: 3, name: '看房记录', iconfont: 'icon-record', to: '' },
  { id: 4, name: '成为房主', iconfont: 'icon-identity', to: '' },
  { id: 5, name: '个人资料', iconfont: 'icon-myinfo', to: '' },
  { id: 6, name: '联系我们', iconfont: 'icon-cust', to: '' }
]

// 默认头像
const DEFAULT_AVATAR = BASE_URL + '/img/profile/avatar.png'

export default function Profile({ history }) {
  // 登录状态
  const [isLogin, setIsLogin] = useState(isAuth())
  // 用户信息
  const [userInfo, setUserInfo] = useState({ avatar: '', nickname: '' })

  // 获取用户信息
  const getUserInfo = useCallback(async () => {
    // 未登录
    if (!isLogin) return

    // 发起请求
    const { data: res } = await API.get('/user')

    if (res.status === 200) {
      const { avatar, nickname } = res.body

      setUserInfo({
        avatar: BASE_URL + avatar,
        nickname
      })
    } else {
      // token 失效的情况，应该将 isLogin 设置为 false
      return setIsLogin(false)
    }
  }, [isLogin])

  useEffect(() => getUserInfo(), [getUserInfo])

  // 退出登录
  const logout = async () => {
    const result = await Modal.confirm({
      title: '提示',
      content: '是否确定退出？'
    })

    // 取消
    if (!result) return

    // 调用退出接口
    await API.post('/user/logout')

    // 移除本地 token
    removeToken()
    // 处理状态
    setTimeout(() => {
      setIsLogin(false)
      setUserInfo({ avatar: '', nickname: '' })
    }, 0)
  }

  return (
    <div className={styles.root}>
      {/* 个人信息 */}
      <div className={styles.title}>
        <img className={styles.bg} src={BASE_URL + '/img/profile/bg.png'} alt="背景图" />
        <div className={styles.info}>
          <div className={styles.myIcon}>
            <img src={userInfo.avatar || DEFAULT_AVATAR} alt="icon" />
          </div>
          <div className={styles.user}>
            <div className={styles.name}>{userInfo.nickname || '游客'}</div>
            {isLogin ? (
              <>
                <div className={styles.edit}>
                  <div className={styles.outBtn}>
                    <Button type="primary" size="small" onClick={logout}>
                      退出
                    </Button>
                  </div>
                  <span className={styles.arrow}>
                    编辑个人资料
                    <span className="iconfont icon-arrowright" />
                  </span>
                </div>
              </>
            ) : (
              <div className={styles.edit}>
                <Button type="primary" size="small" inline onClick={() => history.push('/login')}>
                  去登录
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 九宫格 */}
      <Grid columns={3} style={{ '--gap-vertical': '20px' }}>
        {menus.map(item => (
          <Grid.Item
            className={styles.menuItem}
            key={item.id}
            onClick={() => history.push(`${item.to}`)}
          >
            <i className={`iconfont ${item.iconfont}`} />
            <span>{item.name}</span>
          </Grid.Item>
        ))}
      </Grid>

      {/* 加入我们 */}
      <div className={styles.ad}>
        <img src={BASE_URL + '/img/profile/join.png'} alt="" />
      </div>
    </div>
  )
}
